package com.common.frame.kt

import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.common.frame.mvp.base.BaseActivity
import com.common.frame.mvp.base.BaseFragment
import com.common.frame.mvp.base.BasePresenter
import io.reactivex.disposables.Disposable

/**
 *   kt 扩展函数
 */

fun Disposable.asAutoDisposable(view: View) = AutoDisposable(this, view = view)
fun Disposable.asAutoDisposable(lifecycle: Lifecycle) = AutoDisposable(this,lifecycle = lifecycle)
fun Disposable.asAutoDisposable(activity: BaseActivity<*>) = AutoDisposable(this,baseActivity = activity)
fun Disposable.asAutoDisposable(fragment: BaseFragment<*>) = AutoDisposable(this,baseFragment = fragment)
fun Disposable.asAutoDisposable(presenter: BasePresenter<*>) = AutoDisposable(this,basePresenter = presenter)



class AutoDisposable(private val dis: Disposable,
                     private val view: View? = null,
                     private val lifecycle: Lifecycle? = null,
                     private val baseActivity: BaseActivity<*>? = null,
                     private val baseFragment: BaseFragment<*>? = null,
                     private val basePresenter: BasePresenter<*>? = null
):
    View.OnAttachStateChangeListener, LifecycleEventObserver {

    init {
        if (view?.isAttachedToWindow == true){
            view.addOnAttachStateChangeListener(this)
        }
        lifecycle?.addObserver(this)
        baseActivity?.mCompositeSubscription?.add(dis)
        baseFragment?.mCompositeSubscription?.add(dis)
        basePresenter?.mCompositeSubscription?.add(dis)
    }

    override fun onViewAttachedToWindow(v: View?) = Unit

    override fun onViewDetachedFromWindow(v: View?) {
        if (!dis.isDisposed) dis.dispose()
        view?.removeOnAttachStateChangeListener(this)
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        if (event === Lifecycle.Event.ON_DESTROY) {
            if (!dis.isDisposed) dis.dispose()
            lifecycle?.removeObserver(this)
        }
    }

}
